import pygame
import sys

from pygame.sprite import *#DirtySprite, LayeredDirty, Sprite

from state_manager import *
from settings_manager import *
from button import *
from events import *
path = "data/textures/"


class SettingsScene:
	def __init__(self, screen):
		self.screen = screen

	def create(self):
		self.background = DirtySprite()
		self.background = pygame.image.load(path + str(SettingsManager.settings.resolution[0]) + "_settings_background.jpg")
		
		self.bMinimum = Button(path + "minimum1.png", path + "minimum2.png", path + "minimum3.png")
		self.bMedium = Button(path + "medium1.png", path + "medium2.png", path + "medium3.png")
		self.bMaximum = Button(path + "maximum1.png", path + "maximum2.png", path + "maximum3.png")
		self.bBack = Button(path + "back1.png", path + "back2.png", path + "back3.png")	#back to MainMenu

		#Set buttons in place
		width, height = self.screen.get_rect().width, self.screen.get_rect().height
		bWidth, bHeight = self.bMinimum.rect.width, self.bMinimum.rect.height
		space = 30
		posX=(SettingsManager.settings.resolution[0] / 2) - (bWidth / 4)
		if SettingsManager.settings.resolution[0] == SettingsConst.Minimum[0]:
			posY=122
		elif SettingsManager.settings.resolution[0] == SettingsConst.Medium[0]:
			posY=162
		elif SettingsManager.settings.resolution[0] == SettingsConst.Maximum[0]:
			posY=200

		

		self.bMinimum.rect.x = posX
		self.bMinimum.rect.y = posY

		posY += bHeight
		self.bMedium.rect.x = posX
		self.bMedium.rect.y = posY

		posY += bHeight
		self.bMaximum.rect.x = posX
		self.bMaximum.rect.y = posY


		posX = width - bWidth - space
		posY = height - bHeight - space
		self.bBack.rect.x = SettingsManager.settings.resolution[0] - bWidth
		self.bBack.rect.y = posY

		#Merge all buttons into a group
		self.group = LayeredDirty()
		self.group.add(self.bMinimum, self.bMedium, self.bMaximum, self.bBack)

	def update(self):
		if StateManager.state.window != StateConst.Settings:
			return None #Escape settings updating

		self.manageButtonsClicks()

		self.drawSettings()

	def manageButtonsClicks(self):
		if self.bBack.isClicked():
			StateManager.changeWindow(StateConst.MainMenu)
			StateManager.changeSound(StateConst.SettingsSound)

		if self.bMinimum.isClicked():
			SettingsManager.changeResolution(SettingsConst.Minimum)

		if self.bMedium.isClicked():
			SettingsManager.changeResolution(SettingsConst.Medium)

		if self.bMaximum.isClicked():
			SettingsManager.changeResolution(SettingsConst.Maximum)

	def drawSettings(self):
		self.group.clear(self.screen, self.background)
		update_area = self.group.draw(self.screen)
		pygame.display.update(update_area)
		self.group.update()